package com.vrp3d.common.utils;

import com.vrp3d.common.enums.CommonExceptionEnum;
import com.vrp3d.common.exceptions.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.Enumeration;

/**
 * 解压文件
 *
 * @author vrp3d
 */
@Slf4j
public class UnZipFile {

    /**
     * 判断当前文件是否是zip文件
     *
     * @param filePath 文件路径
     * @return true 是
     */
    public static boolean isZip(String filePath) {
        return isFiles(filePath, "zip");
    }

    /**
     * 判断当前文件是否是制定格式的文件
     *
     * @param filePath 文件路径
     * @param suffix   文件后缀 eg:"zip"
     * @return true 是
     */
    public static boolean isFiles(String filePath, String suffix) {
        // 判断文件路径是否存在
        if (StringUtils.isEmpty(filePath)) {
            return false;
        }
        File file = new File(filePath);
        if (file.isFile() && StringUtils.isEmpty(suffix)) {
            return true;
        }
        String fileName = file.getName();
        String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return suffix.equals(fileSuffix);
    }

    /**
     * 解压zip格式的压缩文件到指定位置
     *
     * @param sourcePath 压缩文件
     * @param targetPath 解压目录
     */
    public static String unZipFiles(String sourcePath, String targetPath) {
        log.info("解压文件:{}", sourcePath);
        System.setProperty("sun.zip.encoding", System.getProperty("sun.jnu.encoding"));
        try {
            (new File(targetPath)).mkdirs();
            File sourceFile = new File(sourcePath);
            // 处理中文文件名乱码的问题
            ZipFile zipFile = new ZipFile(sourcePath, "GBK");
            if ((!sourceFile.exists()) && (sourceFile.length() <= 0)) {
                throw new CommonException(CommonExceptionEnum.FILE_DOES_NOT_EXIST);
            }
            String strPath, gbkPath, strTemp;
            File tempFile = new File(targetPath);
            strPath = tempFile.getAbsolutePath();
            Enumeration<?> e = zipFile.getEntries();
            String result = null;
            while (e.hasMoreElements()) {
                ZipEntry zipEnt = (ZipEntry) e.nextElement();
                gbkPath = zipEnt.getName();
                /*//如果是lh的后缀,返回
                if (gbkPath.endsWith(".lh")) {
                    result = gbkPath;
                }*/

                if (zipEnt.isDirectory()) {
                    strTemp = strPath + File.separator + gbkPath;
                    File dir = new File(strTemp);
                    dir.mkdirs();
                } else {
                    // 读写文件
                    InputStream is = zipFile.getInputStream(zipEnt);
                    BufferedInputStream bis = new BufferedInputStream(is);
                    gbkPath = zipEnt.getName();
                    strTemp = strPath + File.separator + gbkPath;

                    //如果是lh,但不是simple.ls结束的后缀,返回
                    if (gbkPath.endsWith(".lh") && (!gbkPath.endsWith("simple.lh"))) {
                        result = strTemp;
                    }

                    // 建目录
                    String subDir = gbkPath;
                    for (int i = 0; i < subDir.length(); i++) {
                        if ("/".equalsIgnoreCase(subDir.substring(i, i + 1))) {
                            String temp = strPath + File.separator + subDir.substring(0, i);
                            File file = new File(temp);
                            if (!file.exists()) {
                                file.mkdir();
                            }
                        }
                    }
                    FileOutputStream fos = new FileOutputStream(strTemp);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    int c;
                    while ((c = bis.read()) != -1) {
                        bos.write((byte) c);
                    }
                    bos.close();
                    fos.close();
                }
            }
            return result;
        } catch (Exception e) {
            log.info("解压文件失败,目标地址:{}", targetPath);
            e.printStackTrace();
            return null;
        }
    }

}